package com.banmao.youZone.aop.http;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpResponse;
import com.banmao.youZone.consts.CommonConst;
import com.banmao.youZone.entity.History;
import com.banmao.youZone.entity.UserVO;
import com.banmao.youZone.mapper.HistoryMapper;
import com.banmao.youZone.util.RequestUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class HttpAOP {

    @Around("execution(public cn.hutool.http.HttpResponse cn.hutool.http.HttpRequest.execute())")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("[HttpAOP]sending HTTP Request");
        HistoryMapper historyMapper = SpringUtil.getBean(HistoryMapper.class);

        UserVO userVO = CommonConst.USER_THREAD_LOCAL.get();
        if (CommonConst.USER_THREAD_LOCAL.get() == null) {
            userVO = RequestUtil.getSessionUser();
        }

        History history = null;
        if (userVO.getUserId() != -99) {
            Object target = joinPoint.getTarget();
            history = History.builder()
                    .userId(userVO.getUserId())
                    .addDate(DateUtil.date())
                    .success(false)
                    .request_log(String.valueOf(target))
                    .build();
            historyMapper.insert(history);
        }

        try {
            Object proceed = joinPoint.proceed();
            if (history == null) {
                return proceed;
            }
            boolean success = false;
            String responseLog = "";
            if (proceed instanceof HttpResponse response) {
                success = response.getStatus() == 200;
                String resp = String.valueOf(response);
                responseLog = resp.substring(0, Math.min(1024 * 10, resp.length()));
            }
            historyMapper.update(Wrappers.<History>lambdaUpdate()
                    .eq(History::getId, history.getId())
                    .set(History::getSuccess, success)
                    .set(History::getResponse_log, responseLog));
            return proceed;
        } catch (Throwable e) {
            String msg = "";
            if (e.getMessage() != null) {
                msg = e.getMessage().substring(0, Math.min(1024 * 10, e.getMessage().length()));
            }
            if (history != null) {
                historyMapper.update(Wrappers.<History>lambdaUpdate()
                        .eq(History::getId, history.getId())
                        .set(History::getSuccess, false)
                        .set(History::getResponse_log, msg));
            }
            throw e;
        }

    }

}
